import java.util.ArrayList;
import java.util.List;

public class Permute {
    // leetcode 全排列
    // https://leetcode.cn/problems/permutations/description/?envType=study-plan-v2&envId=top-100-liked
    boolean[] vis;
    List<List<Integer>> ret;
    List<Integer> path;
    public List<List<Integer>> permute(int[] nums) {
        vis = new boolean[nums.length];
        ret = new ArrayList<>();
        path = new ArrayList<>();
        dfs(nums);
        return ret;
    }

    private void dfs(int[] nums) {
        if (path.size() == nums.length) {
            ret.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!vis[i]) {
                path.add(nums[i]);
                vis[i] = true;
                dfs(nums);
                vis[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }
}
